//
//  CWJavaScriptApiView.m
//  CWDevelop
//
//  Created by LittoCats on 7/10/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWJavaScriptApiView.h"
#import "CWJavaScriptApiPage.h"

#import "CWViewStaticTouchEventAnalyzer.h"

#import "CWMenu.h"
#import "UIView+CWToast.h"

#define PAGEID action[@"page"]
#define PAGE action[@"__PAGEID"]
#define VIEWID action[@"view"]
#define VIEW action[@"__VIEW"]

@implementation CWJavaScriptApiView

+ (void)analyseAction:(NSMutableDictionary *)action
{
    //解析page
    [CWJavaScriptApiPage analyseAction:action];
    
    NSString *viewId = !VIEWID || [VIEWID isEmpty] ? [PAGE view]._id : VIEWID;
    if (!viewId){
        CWLog(@"[CWJavaScriptAPI] warning : \
              Page.id is not exist < domain : view >.");
    }else{
        UIView *viewInstance = [NSObject findInstanceWithId:viewId];
        viewInstance ? [action setObject:viewInstance forKey:@"__VIEW"] : nil;
    }
}

#pragma mark-
CWJavascriptApi(onClick)
{
    SEL onClick = NSSelectorFromString(@"setOnClickEvent:");
    if ([VIEW respondsToSelector:onClick])
        objc_msgSend(VIEW, onClick, @{@"__function": params, @"__context":[CWJSCONTEXT _id]});
}

#pragma mark-
CWJavascriptApi(popMenu)
{
    UIView *display = [PAGE view];
    display = display ? display : [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [VIEW isEqual:display] ? CGRectZero : [[VIEW superview] convertRect:[VIEW frame] toView:display];
    
    [CWMenu popMenu:params
             inView:display
           fromRect:rect
itemSelectedHandler:^(NSDictionary *menuData, NSInteger menuIndex) {
        [CWJSCALLBACK evaluateWithArguments:@(menuIndex), menuData, nil];
    }];
}

CWJavascriptApi(makeToast)
{
    [VIEW makeToast:params];
}

#pragma mark-
CWJavascriptApi(addSubview)
{
    [params setObject:[CWJSCONTEXT _id] forKey:@"___context"];
    [VIEW addSubview:[UIView instanceWithJSONLayout:params]];
}
@end